package com.sunlands.qdcy.tongzhuo.util;


import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.List;
import java.util.Map;

/**
 * 钉钉工具类
 *
 * @author: anjl
 * @description:
 * @data: 2021/1/19
 **/
@Slf4j
@Component
public class DingUtil {

    @Value("${notice.dingtalk.accessToken}")
    private String dingAccessToken;
    @Value("${notice.dingtalk.logUrl}")
    private String logUrl;

    public  String getLogUrl() {
        return logUrl;
    }

    /**
     * 给钉钉群发送消息方法
     *
     * @param content 消息内容
     * @return
     */
    private String sendMsg(String content) {
        try {
            //获取系统时间戳
            long timestamp = Instant.now().toEpochMilli();
            if (StringUtils.isBlank(dingAccessToken)) {
                log.error("dingAccessToken is null");
                return null;
            }
            String dingUrl = "https://oapi.dingtalk.com/robot/send?access_token=" + dingAccessToken + "&timestamp=" + timestamp;
            String result = HttpUtil.doPost(dingUrl, content);
            return result;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @param content    内容
     * @param isAtAll    是否@所有人 如果写true mobileList失效
     * @param mobileList @人的手机号
     * @return
     */

    public String sendText(String content, boolean isAtAll, List<String> mobileList) {
        //消息内容
        Map<String, String> contentMap = Maps.newHashMap();
        contentMap.put("content", content);
        //通知人
        Map<String, Object> atMap = Maps.newHashMap();
        //1.是否通知所有人
        atMap.put("isAtAll", isAtAll);
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);
        Map<String, Object> reqMap = Maps.newHashMap();
        reqMap.put("msgtype", "text");
        reqMap.put("text", contentMap);
        reqMap.put("at", atMap);
        String contens = JSON.toJSONString(reqMap);

        String result = sendMsg(contens);
        return result;
    }

    public String sendLink(String title, String content, String url) {
        //消息内容
        Map<String, String> link = Maps.newHashMap();
        link.put("text", title + "\n" + content);
        link.put("title", content);
        link.put("picUrl", "https://img.sunlands.wang/deskmate/static/logo.02acab08.png");
        link.put("messageUrl", url);
        Map<String, Object> reqMap = Maps.newHashMap();
        reqMap.put("msgtype", "link");
        reqMap.put("link", link);
        String contens = JSON.toJSONString(reqMap);
        String result = sendMsg(contens);
        return result;
    }

    public String sendActionCard(String title, String content, String url) {
        //消息内容
        Map<String, Object> actionCard = Maps.newHashMap();
        actionCard.put("title", title);
        actionCard.put("text", content);
        actionCard.put("btnOrientation", "0");
//        actionCard.put("singleTitle", "日志详情");
//        actionCard.put("singleURL", url);

//        List<Map<String, String>> list = new ArrayList<>();
//        Map<String, String> button = Maps.newHashMap();
//        button.put("title","详细日志");
//        button.put("actionURL",url);
//        list.add(button);
//        actionCard.put("btns", list);
        Map<String, Object> reqMap = Maps.newHashMap();
        reqMap.put("msgtype", "actionCard");
        reqMap.put("actionCard", actionCard);
        String contens = JSON.toJSONString(reqMap);
        String result = sendMsg(contens);
        return result;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        try {

            Integer i = null;
            if (i < 1) {

            }
        } catch (Exception e) {
            DingUtil dingUtil = new DingUtil();
            dingUtil.logUrl = "http://62.234.206.99:32000/explore?orgId=1&left=";
            dingUtil.dingAccessToken = "5bd033715c904019e45e2035cbb6f7ac72565bb8313e8f6ae5adbac4b5bbe476";
//            String result = dingUtil.sendLink("[系统异常]", "报警====>" + e.getMessage(), "https://www.baidu.com/");'
//            String url = "http://62.234.206.99:32000/explore?orgId=1&left=[\"now-6h\",\"now\",\"Loki\",{\"expr\":\"{namespace=\\\"tongzhuo\\\"}|= \\\"c0e37924118d4c01bd0cd2d84d87eabe\\\"\"},{\"mode\":\"Logs\"},{\"ui\":[true,true,true,\"signature\"]}]";
//              String url = "http://62.234.206.99:32000/explore?orgId=1&left=%5B%22now-6h%22,%22now%22,%22Loki%22,%7B%22expr%22:%22%7Bnamespace%3D%5C%22tongzhuo%5C%22%7D%7C%3D%20%5C%22c0e37924118d4c01bd0cd2d84d87eabe%5C%22%22%7D,%7B%22mode%22:%22Logs%22%7D,%7B%22ui%22:%5Btrue,true,true,%22signature%22%5D%7D%5D";
            String url = dingUtil.logUrl + URLEncoder.encode("[\"now-6h\",\"now\",\"Loki\",{\"expr\":\"{namespace=\\\"tongzhuo\\\"}|= \\\"c0e37924118d4c01bd0cd2d84d87eabe\\\"\"},{\"mode\":\"Logs\"},{\"ui\":[true,true,true,\"signature\"]}]", "utf-8");
            String content = "## 系统异常[tz-user-center]\n" +
                    "1. [一分钟发生次数1次]\n" +
                    "2. [ip]：127.0.0.1\n" +
                    "3. [requestId]：8dbaa4b2d4b3427999c5f3aa4b9590fe\n" +
                    "4. [method]：GET\n" +
                    "5. [uri]：/users/user-homepage/312\n" +
                    "6. [paramInfo]：null\n" +
                    "7. [datetime]：2021-01-19T11:22:32Z\n";

            url = "[详情]" + "(" + url + ")";
            String result = dingUtil.sendActionCard("[系统异常]", content + url, null);
//            String result = dingUtil.sendText(content + url, false, null);
            log.info("result = {}", result);
        }


    }
}
